package Test.test4.exam3;


import java.io.*;
import java.net.Socket;
import java.util.List;

public class ServerThread extends Thread {
    private Socket s;
    private List<Socket> sockets;

    public ServerThread(Socket s, List<Socket> sockets) {
        this.s = s;
        this.sockets = sockets;
    }

    @Override
    public void run() {
        BufferedReader br = null;//创建输入流读取数据
        PrintWriter pw = null;//创建输出流打印数据
        try {
            System.out.println(Thread.currentThread().getId() + ":" + Thread.currentThread().getName());//打印当前的线程及id
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));//获取来自客户端发来的数据
            while (true) {
                String str = null;
                str = br.readLine();//读取客户端发来的数据
                System.out.println(Thread.currentThread().getName() + "发来的内容是" + str);//打印客户端发来的数据
               for (Socket s : sockets) {//向每个客户端发送接收到的数据
                   pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));//获取当前客户端的输出流
                   pw.println(str);//向客户端写入数据
                   pw.flush();
                   System.out.println("已将客户端法来的数据" + str + "转发到其它客户端");}
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }
    }


}
